package com.bjfu.gmms.servlet.departmentHeadServlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.ResearchDirectionMapper;
import com.bjfu.gmms.model.ResearchDirection;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/researchDirectionOperate")
public class ResearchDirectionOperateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");

        try(SqlSession sqlSession = MyBatisUtil.getSqlSession("development")){
            ResearchDirectionMapper mapper = sqlSession.getMapper(ResearchDirectionMapper.class);
            if ("add".equals(action)) {
                // 处理添加研究方向的逻辑
                String customIdPrefix = request.getParameter("researchId");
                String customIdSuffix = request.getParameter("customIdSuffix");
                String researchId = customIdPrefix + customIdSuffix;
                String researchName = request.getParameter("researchName");
                ResearchDirection researchDirection = new ResearchDirection();
                researchDirection.setResearchId(researchId);
                researchDirection.setResearchDirection(researchName);
                researchDirection.setSecondaryDisciplineId(customIdPrefix);
                int result = mapper.addResearchDirection(researchDirection);
                sqlSession.commit();  // 提交事务
                if (result > 0) {
                    response.getWriter().write("Research direction added successfully.");
                } else {
                    response.getWriter().write("Failed to add research direction.");
                }
            } else if("delete".equals(action)) {
                String researchId = request.getParameter("researchId");
                int result = mapper.deleteResearchDirection(researchId);
                sqlSession.commit();
                if (result > 0) {
                    response.getWriter().write("Research direction delete successfully.");
                } else {
                    response.getWriter().write("Failed to delete research direction.");
                }
            }
        }
    }
}
